﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RooHui.Infrastructure.Entities.Entity;
using RooHui.Portal.Biz.Model;
using RooHui.Tool;
using System.Web.Security;
using RooHui.Infrastructure.Entities.EFContext;
using RooHui.Infrastructure.Entities.EntityCode;
using RooHui.Portal.Biz.Content;
using RooHui.Infrastructure.Component.WorkPool;
using RooHui.Infrastructure.Component.WorkPool.WorkHandle.Email;
using RooHui.Infrastructure.Configuration;
using RooHui.Infrastructure.Component.WorkPool.WorkHandle.ShortMessage;
using System.Web;
using RooHui.Infrastructure.Entities.Enum;
using System.Text.RegularExpressions;
using System.Transactions;
using RooHui.Infrastructure.Entities;

namespace RooHui.Portal.Biz
{

    public class MemberBiz
    {
        #region Account
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="NoEmail">true:不发邮件</param>
        /// <returns>注册失败返回null</returns>
        public static Member Register(Member member, bool NoEmail = false)
        {
            if (member != null && !String.IsNullOrEmpty(member.UserName)
                    && UserNotExists(member.UserName))
            {
                var token = new AccountToken()
                {
                    ExpireDate = DateTime.Now.AddDays(7),
                    Token = Guid.NewGuid().ToString(),
                    UserName = member.UserName
                };
                member.Token = token.Token;
                member.Password = AesAlgorithm.Encrypt(member.Password);
                member = member.PostAdd();
                new Account()
                {
                    UserName = member.UserName,
                    Platfrom = AccountPlatfrom.HuiFu,
                    AccountNo = "",
                    BalanceAmount = 0,
                    FrozenAmount = 0
                }.PostAdd();
                if (member != null)
                {
                    return member;
                }
            }
            return null;
        }
        private static string BuildFixToken(AccountToken token)
        {
            string str = token.ToJson();
            return EncodeByBase64.Encode(str);
        }
        public static Member CheckToken(string token)
        {
            if (String.IsNullOrEmpty(token))
            {
                return null;
            }
            token = EncodeByBase64.Decode(token);
            var accountToken = token.ToObject<AccountToken>();
            if (accountToken != null)
            {
                var user = new Member().Find(accountToken.UserName);
                if (user != null)
                {
                    if (user.Token == accountToken.Token
                        && accountToken.ExpireDate > DateTime.Now)
                    {
                        user.Token = Guid.NewGuid().ToString();
                        user.PostModify();
                        return user;
                    }
                }
            }
            return null;
        }
        public static Member Activation(string token)
        {
            var member = CheckToken(token);
            if (member != null)
            {
                member.IsActive = true;
                member.EmailCheck = true;
                if (member.PostModify() != null)
                {
                    return member;
                }
            }
            return null;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="rememberMe"></param>
        /// <returns>登录失败返回null</returns>
        public static Member Login(string userName, string password, bool rememberMe = false)
        {
            var member = new Member().Find(userName);
            if (member != null && member.Status == ItemStatus.Enable)
            {
                if (member.Password == AesAlgorithm.Encrypt(password))
                {
                    if (!member.IsActive)
                    {
                        return new Member() { IsActive = false };
                    }
                    FormsAuthentication.SetAuthCookie(userName, rememberMe);
                    new MemberLog()
                    {
                        OperateContent = "登录",
                        OperateIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"],
                        OperateTime = DateTime.Now,
                        OperateType = Infrastructure.Entities.Enum.MemberOperateType.Login,
                        UserName = userName
                    }.PostAdd();
                    return member;
                }
            }
            return null;
        }
        public static void LogOut()
        {
            System.Web.Security.FormsAuthentication.SignOut();
        }
        /// <summary>
        /// true:不存在 false:存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool UserNotExists(string userName)
        {
            if (!String.IsNullOrEmpty(userName))
            {
                using (Context ctx = new Context())
                {
                    return !ctx.Member.Any(c => c.UserName == userName);
                }
            }
            return false;
        }
        /// <summary>
        /// 发重置密码邮件
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool ResendForgotPasswordMail(string userName)
        {
            var member = new Member().Find(userName);
            if (member != null)
            {
                var token = new AccountToken()
                {
                    ExpireDate = DateTime.Now.AddDays(1),
                    Token = Guid.NewGuid().ToString(),
                    UserName = userName
                };
                member.Token = token.Token;
                if (member.PostModify() != null)
                {
                    string toMember = EmailBuilder.BuildResetPasswordEmail(
                        member.UserName, BuildFixToken(token));
                    if (!String.IsNullOrEmpty(toMember))
                    {
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                         new NormalNotifyEmail()
                         {
                             Message = toMember,
                             Title = SiteSettings.SiteName + "--密码重置验证",
                             Recipient = member.UserName
                         });
                    }
                }
                return true;
            }
            return false;
        }
        public static Member ChangePassword(string userName, string password)
        {
            if (!String.IsNullOrEmpty(userName) &&
                !String.IsNullOrEmpty(password))
            {
                var member = new Member().Find(userName);
                if (member != null)
                {
                    member.Password = AesAlgorithm.Encrypt(password);
                    if (member.PostModify() != null)
                    {
                        new MemberCache().RefreshItem(userName);
                        return member;
                    }
                }
            }
            return null;

        }
        /// <summary>
        /// 更改密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static User ChangePassword(string userName, string oldpassword, string password)
        {
            if (!String.IsNullOrEmpty(userName) &&
                !String.IsNullOrEmpty(password))
            {
                var user = new User().Find(userName);
                if (user != null)
                {
                    if (user.Password != AesAlgorithm.Encrypt(oldpassword))
                    {
                        return null;
                    }
                    user.Password = AesAlgorithm.Encrypt(password);
                    if (user.PostModify() != null)
                    {
                        return user;
                    }
                }
            }
            return null;
        }
        
        public static Member ReSendActiveMail(string username)
        {
            if (String.IsNullOrEmpty(username))
            {
                return null;
            }
            var member = new Member().Find(username);
            if (member != null && !member.IsActive)
            {
                var token = new AccountToken()
                {
                    ExpireDate = DateTime.Now.AddDays(7),
                    Token = Guid.NewGuid().ToString(),
                    UserName = member.UserName
                };
                member.Token = token.Token;
                member = member.PostModify();
                if (member != null)
                {
                    string toMember = EmailBuilder.BuildRegisterActivtionEmail(
                               member.UserName, BuildFixToken(token));
                    if (!String.IsNullOrEmpty(toMember))
                    {
                        WorkPool.Append<NormalNotifyEmail>(WorkType.email_for_normalnotify,
                        new NormalNotifyEmail()
                        {
                            Message = toMember,
                            Title = SiteSettings.SiteName + "--账号激活邮件",
                            Recipient = member.UserName
                        });
                    }
                    return member;
                }
            }
            return null;
        }
        public static Member ChangeInfo(string username, string photo, string nickname, string birthday,
            int gender, int areaCode, int location, string email, string phone, string qq)
        {
            var user = new Member().Find(username);
           
            return null;
        }

        #endregion

        /// <summary>
        /// 获取最后一次用户操作日志
        /// </summary>
        /// <param name="userName"></param>
        public static MemberLog GetLastMemberLog(string userName,MemberOperateType operateType)
        {
            using (Context ctx = new Context())
            {
                var item = ctx.MemberLog.Where(c => c.UserName == userName && c.OperateType == (int)operateType)
                    .OrderByDescending(c => c.ID)
                    .FirstOrDefault();
                if (item == null)
                {
                    return null;
                }
                return new MemberLog().Set(item);
            }
        }
        public static void SetMemberAuth(string username, string cardId,string page1,string page2)
        {
            if (new Regex("(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|x)$)").IsMatch(cardId))
            {
                var member = new Member().Find(username);
                if (member != null)
                {
                    if (!member.IDCardCheck)
                    {
                        using (TransactionScope scope = new TransactionScope())
                        {
                            new Secret().FindAll(c => c.UserName == username && c.Type == (int)SecretType.IDCard).ForEach(c => {
                                c.PostDelete();
                            });
                            var p1 = new Secret()
                            {
                                CreateTime = DateTime.Now,
                                Key = "page1",
                                Type = SecretType.IDCard,
                                UserName = username,
                                Value = page1
                            }.PostAdd();

                            var p2 = new Secret()
                            {
                                CreateTime = DateTime.Now,
                                Key = "page2",
                                Type = SecretType.IDCard,
                                UserName = username,
                                Value = page2
                            }.PostAdd();

                            member.IDCardNo = cardId;
                            if (p1 != null && p2 != null && member.PostModify() != null)
                            {
                                scope.Complete();
                            }
                        }
                    }
                }
            }
        }

        #region 资金相关
        public static Account GetCapitalInfo(string userName)
        {
            using (Context ctx = new Context())
            {
                var account = GetAccount(userName);
                var data = (from o in ctx.Order
                            join p in ctx.Project
                              on o.ProjectId equals p.ID
                            where o.UserName == userName
                            select new { o.Amount, p.Status })
                          .ToList();
                if (data.Any())
                {
                    var frozenAmount=data.Sum(c=>c.Amount);
                    if (account.FrozenAmount != frozenAmount)
                    {
                        LogHelper.Write(CommonLogger.Alter, LogLevel.Info,
                            String.Format("用户：{0}，账号冻结额与项目冻结额不一致，帐户下显示为：{1}，而冻结项目总额为：{2}",
                            userName, account.FrozenAmount, frozenAmount));
                    }
                    account.FrozenAmount = frozenAmount;
                    account.FrozenCount = data.Count(c => c.Status == (int)ProjectStatus.Publish);
                }

                var paybackdata = (from c in ctx.PayBack
                                   where c.UserName == userName && c.Status == (int)ItemStatus.Enable
                                   select new { c.PayBackInterest, c.PayBackedInterest, c.PayBackPrincipal, c.PayBackedPrincipal })
                                  .ToList();

                account.Corpus = paybackdata.Sum(c => c.PayBackPrincipal) - paybackdata.Sum(c => c.PayBackedPrincipal);
                account.Accrual = paybackdata.Sum(c => c.PayBackInterest) - paybackdata.Sum(c => c.PayBackedInterest);
                account.TotalAccrual = paybackdata.Sum(c => c.PayBackInterest);
                account.TotalCorpus = paybackdata.Sum(c => c.PayBackPrincipal);
                return account;
            }
        }
        public static Account GetAccount(string userName)
        {
            var account = new Account().Find(userName);
            if (account != null)
            {
                return account;
            }
            else
            {
                if (new Member().Find(userName) != null)
                {
                    account = new Account()
                    {
                        BalanceAmount = 0,
                        FrozenAmount = 0,
                        Platfrom = AccountPlatfrom.HuiFu,
                        UserName = userName
                    }.PostAdd();
                    return account;
                }
            }
            return null;
        }
       
        public static RechargCallBackModel TallyForRechargeCallBack(string token)
        {
            //Account表
            //AmountOperation表
            //AccountHistory表
            return null;
        }

        /// <summary>
        /// 提现
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="amount"></param>
        /// <returns></returns>
        public static WithdrawModel TallyForWithdraw(string userName, decimal amount)
        {
            return null;
        }
        public static WithdrawCallBackModel TallyForWithdrawCallBack(string token)
        {
            //Account表
            //AmountOperation表
            //AccountHistory表
            return null;
        }

        
        public static ItemListBox<AmountOperation> GetAccountOperations(string username, string startDate = "", string endDate = "",int page=0,int pageSize=20)
        {
            using (Context ctx = new Context())
            {
                var list = from c in ctx.AmountOperation
                           where c.UserName == username
                           select c;
                DateTime startDt = DateTime.Now;
                if (!String.IsNullOrEmpty(startDate) && DateTime.TryParse(startDate, out startDt))
                {
                    list = list.Where(c => c.CreateTime >= startDt);
                }
                DateTime endDt = DateTime.Now;
                if (!String.IsNullOrEmpty(endDate) && DateTime.TryParse(endDate, out endDt))
                {
                    endDt = endDt.Add(new TimeSpan(23, 59, 59));
                    list = list.Where(c => c.CreateTime <= endDt);
                }
                var data = list.OrderByDescending(c => c.ID)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c => new AmountOperation().Set(c))
                    .ToList();
                return new ItemListBox<AmountOperation>(data).BuildPage(list.Count(), page, pageSize, new PageParameter() { Style = "Home" });
            }
        }
        #endregion
    }
}
